// src/stores/materialType.ts
import { defineStore } from 'pinia';
import axios from '@/plugins/axios';

// 物资类型数据接口
export interface MaterialType {
  id: number;
  typeNumber: string;
  name: string;
  description: string;
  createTime: string;
}

// 物资类型表单字段配置
export const materialTypeFields = [
  {
    key: 'typeNumber',
    label: '类型编号',
    type: 'text',
    placeholder: '请输入类型编号（如 MT001）',
    maxLength: 10,
  },
  {
    key: 'name',
    label: '名称',
    type: 'text',
    placeholder: '请输入物资类型名称',
    maxLength: 50,
  },
  {
    key: 'description',
    label: '描述',
    type: 'textarea',
    placeholder: '请输入物资类型描述（可选）',
    maxLength: 500,
  },
];

export const useMaterialTypeStore = defineStore('materialType', {
  state: () => ({
    materialTypes: [] as MaterialType[],
  }),
  actions: {
    // 获取物资类型列表（无分页）
    async fetchMaterialTypes() {
      try {
        const response = await axios.get('/material-types');
        if (response.data.code === 200) {
          this.materialTypes = response.data.data;
          return this.materialTypes;
        }
        throw new Error(response.data.message || '获取物资类型失败');
      } catch (error) {
        throw new Error('获取物资类型失败');
      }
    },
    // 创建物资类型
    async createMaterialType(data: { typeNumber: string; name: string; description: string }) {
      const response = await axios.post('/material-types', data);
      if (response.data.code === 200) {
        return response.data.data;
      }
      throw new Error(response.data.message || '创建物资类型失败');
    },
    // 更新物资类型
    async updateMaterialType(data: MaterialType) {
      const response = await axios.put('/material-types', data);
      if (response.data.code === 200) {
        return response.data.data;
      }
      throw new Error(response.data.message || '更新物资类型失败');
    },
    // 删除物资类型
    async deleteMaterialType(id: number) {
      const response = await axios.delete(`/material-types/${id}`);
      if (response.data.code ===  200) {
        return response.data.data;
      }
      throw new Error(response.data.message || '删除物资类型失败');
    },
  },
});